/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.component.channel.impl.socket.server;

import com.xuexiang.xdlink.component.channel.IChannel;
import com.xuexiang.xdlink.component.channel.OnChannelListener;
import com.xuexiang.xdlink.component.channel.entity.ConnectStatusEnum;
import com.xuexiang.xdlink.component.channel.impl.AbstractDataReceiver;
import com.xuexiang.xdlink.logs.DCFLog;
import com.xuexiang.xdlink.util.Utils;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单一的、长连接Socket服务端 通信通道【等到有客户端连接成功了才算连接成功，只能是一对一的连接】
 *
 * @author xuexiang
 * @since 2018/8/24 上午9:44
 */
public class SingleServerSocketChannel extends AbstractServerSocketChannel {

    /**
     * 构造函数
     *
     * @param port 服务开启的端口号
     */
    public SingleServerSocketChannel(int port) {
        super(port, true);
    }

    /**
     * 构造函数
     *
     * @param port 服务开启的端口号
     * @param isAutoSwitchThread 是否自动切换线程
     */
    public SingleServerSocketChannel(int port, boolean isAutoSwitchThread) {
        super(port, isAutoSwitchThread);
    }

    /**
     * 启动服务
     */
    @Override
    protected void startServer() {
        try {
            //只接收一个连接
            mServerSocket = new ServerSocket(mPort, 1);
            mServerSocket.setReuseAddress(true);

            // 调用ServerSocket的accept()方法，等待下位机的连接，这里是阻塞的方法
            mSocket = mServerSocket.accept();
            mSocket.setTcpNoDelay(true);
            handleConnectResult(true);

        } catch (Exception e) {
            e.printStackTrace();
            DCFLog.e("Socket[single server] start failed!", e);
            handleConnectResult(false);
            Utils.closeIO(mSocket);
            mSocket = null;
        }
    }

    @Override
    public boolean isOpen() {
        return super.isOpen() && mServerSocket != null && mSocket != null && mSocket.isConnected();
    }

    /**
     * 处理连接结果
     *
     * @param isConnectSuccess 是否连接成功
     */
    private void handleConnectResult(boolean isConnectSuccess) {
        if (isConnectSuccess) {
            DCFLog.i("Socket[single server] start success...");

            startAcceptData(new SocketDataReceiver(mSocket, getChannelListener()));

            updateConnectStatus(ConnectStatusEnum.CONNECT_SUCCESS);// 打开设备成功,发送命令
        } else {
            updateConnectStatus(ConnectStatusEnum.CONNECT_FAILED);
        }
    }

    /**
     * Socket数据接收器
     *
     * @author xuexiang
     * @since 2018/8/24 上午11:00
     */
    protected class SocketDataReceiver extends AbstractDataReceiver {

        public SocketDataReceiver(Socket socket, OnChannelListener listener) {
            super(socket, listener);
        }

        @Override
        public IChannel getChannel() {
            return SingleServerSocketChannel.this;
        }

    }

}
